<template>
  <div class="container" ref="mainCon">
    <!-- 标题 -->
    <topTitle :titleText="titleText"></topTitle>
    <!-- 搜索 -->
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="区域" class="row-padding-bottom">
              <el-cascader
                ref="manageArea"
                v-model="areaId"
                :options="areasOptions"
                @change="getAreaId"
                clearable
                filterable
                :props="{ checkStrictly: true }"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-form-item label="">
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <exportBtn
              v-if="!isShowAdd"
              :dataLen="tableList.length"
              :filterField="filterField"
              api="api-s/report/export_SYS_TEMPLATE"
            ></exportBtn>
          </el-form-item>
          <!-- <el-form-item>
                        <exportBtn :dataLen="tableList.length" :filterField="filterField" api="api-s/report/export_SYS_TEMPLATE"></exportBtn>
                    </el-form-item> -->
          <!-- <el-form-item>
                        <el-button type="primary" icon="icon iconfont iconchazhao1" class="commonBtn" @click="searchList"></el-button>
                    </el-form-item> -->
          <!-- <el-form-item v-show="isShowAdd">
                        <el-button class="commonBut saveBtn funComBut" icon="icon iconfont icontianjia" @click="toAdd">
                            <span class="opetareText">添加</span>
                        </el-button>
                    </el-form-item> -->
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <exportBtn
            :dataLen="tableList.length"
            :filterField="filterField"
            api="api-s/report/export_SYS_TEMPLATE"
          ></exportBtn>
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icontianjia"
            @click="toAdd"
          >
            <span class="opetareText">添加</span>
          </el-button>
        </div>
        <!-- 表格 -->
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="areaName"
            label="区域"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="function"
            label="涉及功能"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="pages"
            label="涉及页面"
            :formatter="formatTd"
            width="280"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.pages"
                :columnName="'pages'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="fileName"
            label="附件"
            align="left"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <el-link type="primary" v-if="checkImg(scope.row.templatePath)">{{
                scope.row.fileName
              }}</el-link>
              <el-image
                class="previewImg"
                style="width: 100%; height: 56px"
                :src="scope.row.templatePath"
                :preview-src-list="[scope.row.templatePath]"
                v-if="checkImg(scope.row.templatePath)"
              ></el-image>
              <el-link
                type="primary"
                v-if="!checkImg(scope.row.templatePath)"
                @click="lookResult(scope.row.templatePath)"
                >{{ scope.row.fileName }}</el-link
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column label="操作" align="left">
            <template slot-scope="scope">
              <el-link type="primary" @click="updateData(scope.row)"
                >修改</el-link
              >
              <el-link type="primary" @click="deleteData(scope.row)"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- 分页 -->
        <Pagination
          ref="pagination"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
      <!-- 新增弹窗 -->
      <el-dialog
        :title="tempDialogTitle"
        :visible.sync="formVisible"
        :close-on-click-modal="false"
        @close="cancelEdit"
        custom-class="brand-dialog-min-width"
        width="800px"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <el-form
          :model="formData"
          :rules="formRules"
          ref="formData"
          label-width="125px"
        >
          <el-form-item label="区域" prop="areaId">
            <el-cascader
              ref="areas"
              v-model="formArea"
              :options="areasOptions"
              @change="getFormAreaId"
              clearable
              filterable
              placeholder="请选择"
              class="form-item"
              :props="{ checkStrictly: true }"
              :disabled="disabled"
            ></el-cascader>
          </el-form-item>
          <el-form-item prop="type" label="涉及功能">
            <el-select
              v-model="formData.type"
              placeholder="请选择"
              class="form-item"
              @change="changeFunc"
              :disabled="disabled"
            >
              <el-option
                v-for="item in involveFuncArr"
                :key="item.type"
                :label="item.function"
                :value="item.type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="involvePage" label="涉及页面">
            <span>{{ formData.involvePage }}</span>
          </el-form-item>
          <el-form-item label="附件" prop="enclosure">
            <uploadAnnex
              @getFileList="getFileList"
              :limitationFactor="limitationFactor"
              @getFile="getFile"
              :upLoadFile="upLoadFile"
            />
          </el-form-item>
          <uploadResult
            :resultList="upLoadFile"
            style="margin-left: 120px !important"
            @callBackResult="callBackResult"
          />
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model.trim="formData.remark"
              autocomplete="off"
              placeholder="请填写备注"
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="cancelEdit" class="cancel">取消</el-button>
          <el-button
            type="primary"
            @click.native="saveTemp"
            class="save"
            :loading="isSaveLoading"
            >保存</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import uploadResult from '@/components/publicCom/uploadResult'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'templateManagementList',
  mixins: [scrollTable],
  components: {
    uploadResult,
  },
  data() {
    var UploadFile = (rule, value, callback) => {
      if (this.upLoadFile.length === 0) {
        return callback(new Error('附件不能为空'))
      } else {
        callback()
      }
    }
    return {
      titleText: '模板管理',
      requestUrl: '/api-f/template/findbypage',
      //表格数据
      tableList: [],
      isShow: false, //列表加载
      loading: false,
      filterField: {
        areaId: '',
      },
      areaId: '', //区域
      pageSize: 20,
      pageNo: 1,
      isShowAdd: true,
      tempDialogTitle: '',
      formVisible: false,
      formArea: [],
      formData: {
        areaId: '',
        type: '',
        remark: '',
        involvePage: '(选择涉及功能后查看)',
        fileJson: '',
        paramId: '',
      },
      involveFuncArr: [],
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 1, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip:
          '模板附件支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传1个附件，附件大小不超过5M', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      upLoadFile: [], //附件
      srcList: [],
      oldSrcList: [],
      disabled: false,
      formRules: {
        areaId: [
          {
            required: true,
            message: '区域不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        type: [
          {
            required: true,
            message: '涉及功能不能为空',
            trigger: 'change',
          },
        ],
        involvePage: [
          {
            required: true,
            message: '涉及页面不能为空',
            trigger: 'change',
          },
        ],
        enclosure: [
          {
            required: true,
            validator: UploadFile,
            trigger: 'change',
          },
        ],
      },
      isSaveLoading: false,
      id: '',
    }
  },
  computed: { ...mapState(['areasOptions']) },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    // this.isShowAdd= this.$store.state.buttonLimitsArr.indexOf('companyaccount:add') > -1;
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
  },
  mounted() {},
  activated() {},
  watch: {
    upLoadFile(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('enclosure')
      }
    },
  },
  methods: {
    ...mapActions(['getAreas']),
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
    },
    getFormAreaId() {
      this.formData.areaId = this.formArea[this.formArea.length - 1]
    },
    // 添加
    toAdd() {
      this.getFunc()
      this.tempDialogTitle = '添加模板'
      this.formVisible = true
      this.disabled = false
      this.formArea = []
      this.formData.areaId = ''
    },
    changeFunc() {
      this.involveFuncArr.map((item, index) => {
        if (item.type === this.formData.type) {
          this.formData.involvePage = item.pages[0]
          this.formData.paramId = item.paramId
        }
      })
      // if(this.formData.type == 1) {
      //     this.formData.involvePage = "项目端-维权公示牌-查看范例";
      // }else {
      //     this.formData.involvePage = "项目端-专户列表-添加工资专户弹窗-下载模板";
      // }
    },
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFile(val) {
      this.upLoadFile = val
    },
    callBackResult(val) {
      this.upLoadFile = val
    },
    cancelEdit() {
      this.formVisible = false
      this.upLoadFile = []
      this.$refs.formData.resetFields()
    },
    // 修改功能
    updateData(row) {
      this.getFunc()
      this.formVisible = true
      this.tempDialogTitle = '修改模板'
      this.getDetail(row)
      this.disabled = true
    },
    getDetail(row) {
      this.axios({
        method: 'post',
        url: '/api-f/template/detail',
        data: {
          templateId: row.id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.formArea = response.data.areaId
            this.formData.areaId = response.data.areaId
            this.formData.type = response.data.type
            this.formData.involvePage = response.data.pages[0]
            this.upLoadFile = JSON.parse(response.data.fileJson)
            this.id = response.data.id
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('获取失败')
        })
    },
    // 涉及功能下拉
    getFunc() {
      this.axios({
        method: 'get',
        url: '/api-f/template/menu',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.involveFuncArr = response.data
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('获取失败')
        })
    },
    // 添加、修改模板
    saveTemp() {
      this.isSaveLoading = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.formData.fileJson = JSON.stringify(this.upLoadFile)
          if (this.tempDialogTitle === '添加模板') {
            this.saveDept(this.tempDialogTitle)
          } else if (this.tempDialogTitle === '修改模板') {
            this.saveDept(this.tempDialogTitle)
          }
        } else {
          this.isSaveLoading = false
          return false
        }
      })
    },
    saveDept(tempDialogTitle) {
      var successTitle, addUrl, Data
      if (tempDialogTitle == '添加模板') {
        addUrl = '/api-f/template/add'
        successTitle = '添加成功'
        this.$delete(this.formData, 'id')
      } else {
        addUrl = '/api-f/template/update'
        successTitle = '修改成功'
        this.formData.id = this.id
        this.$delete(this.formData, 'paramId')
      }
      this.axios({
        method: 'post',
        url: addUrl,
        data: this.formData,
      })
        .then((resp) => {
          this.isSaveLoading = false
          if (!resp.data.hasError) {
            this.$message({
              message: successTitle,
              type: 'success',
            })
            this.formVisible = false
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: resp.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    // 删除
    deleteData(row) {
      this.$confirm('删除后对应功能将无法使用该模板，是否确认删除?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.toDel(row.id)
        })
        .catch(() => {})
    },
    toDel(id) {
      this.axios({
        method: 'post',
        url: '/api-f/template/delete',
        data: {
          id: id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            //删除成功刷新列表
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('删除失败')
        })
    },
    lookResult(url) {
      window.open(url)
    },
    getName(url) {
      if (url) {
        const fileName = url.lastIndexOf('/') // 取到文件名开始到最后一个点的长度
        const fileNameLen = url.length // 取到文件名长度
        const fileType = url.substring(fileName + 1, fileNameLen) // 截
        return fileType
      }
    },
    checkImg(item) {
      var str = this.getName(item)
      if (str) {
        let arr = str.split('.')
        let name = arr[arr.length - 1]
        if (['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG'].includes(name)) {
          return true
        }
        return false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.mainCon {
  top: 197px;
}
.form-item {
  width: 300px;
}
.previewImg {
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  /deep/.el-image__preview {
    opacity: 0;
  }
  /deep/.el-image__error {
    opacity: 0;
  }
  // transform: translateX(-50%)
}
.a_link {
  color: #409eff;
}
.mouseOn {
  cursor: pointer;
}
@import '../../../static/css/filterArea.less';
</style>
